package stdio.costa.imoca.task;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import stdio.costa.imoca.model.Image;
import stdio.costa.imoca.model.Preview;
import stdio.costa.imoca.spi.ImageServiceFactory;

@Service
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class AsyncPostcardPreviewCleaner implements Cleaner {

	@PersistenceContext
	private EntityManager entityManager;
	
	@Autowired
	private ImageServiceFactory imageServiceFactory;
	
	@SuppressWarnings("unchecked")
	@Async
	@Override
	public void clean() {
		Query query = entityManager.createNamedQuery("Postcard.findCloudReadyPreviews");
		List<Preview> previews = query.getResultList();
		for(Preview preview : previews) {
			migrateToCloud(preview);
		}
	}

	private void migrateToCloud(Preview preview) {
		migrateToCloud(preview.getFront());
		migrateToCloud(preview.getBack());
	}
	
	private void migrateToCloud(Image image) {
		imageServiceFactory.getImageService().create(image);
		image.setData(null);
		entityManager.merge(image);
	}
}
